package com.easyOrder.service.common;

import com.easyOrder.core.exception.api.InvalidPasswordException;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by liutao on 2017/7/15.
 */
@Service
public class CommonService {

    /**
     * 默认密码加密算法
     */
    private static final String DEFAULT_ALGORITHM = "SHA-256";

    /**
     * 密码加密算法。
     */
    private String passwordAlgorithm;

    /**
     * 密码加密混淆文本。
     */
    private String passwordSalt;

    public CommonService() {
        passwordAlgorithm = DEFAULT_ALGORITHM;
        passwordSalt = "";
    }

    /**
     * 对密码进行加密后输出
     *
     * @param password 明文密码
     * @return 密文密码
     */
    @SuppressWarnings("restriction")
    public String encryptPassword(String password) {
        String input = password;
        if (passwordSalt.length() != 0) {
            input += passwordSalt;
        }
        sun.misc.BASE64Encoder base64Encoder = new sun.misc.BASE64Encoder();
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(passwordAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new InvalidPasswordException();
        }
        return base64Encoder.encode(messageDigest.digest(input.getBytes()));
    }
}
